package org.daochong.fastdev.funcs;

import java.sql.SQLException;

import org.daochong.fastdev.Context;
import org.daochong.fastdev.Function;
import org.daochong.fastdev.OperationId;
import org.daochong.fastdev.util.FastDevUtils;
import org.daochong.lang.BeanUtil;
import org.daochong.lang.StringUtils;

public class UpdateFunction implements Function {

	public boolean is(String id) {
		return FastDevUtils.operEntity("update", id) || FastDevUtils.operEntity("updateWithoutNull", id);
	}

	public void exec(String key, String prop, Context context)  throws SQLException{
		if (!is(key))
			throw new RuntimeException("Function  not match [" + key + "]");
		prop = BeanUtil.formatString(prop, context);
		if ("update".equals(key)) {
			for (OperationId oid : FastDevUtils.operationIds(prop)) {
				Object entity = context.getClassMappingFactory().getEntity(oid.getId(), context.getParameters());
				Object obj = context.getJpaOperations().update(entity,
						BeanUtil.getExtDatas(entity, context.getParameters()));
				context.add(oid, obj);
			}
		} else if ("updateWithoutNull".equals(key)) {
			for (OperationId oid : FastDevUtils.operationIds(prop)) {
				Object entity = context.getClassMappingFactory().getEntity(oid.getId(), context.getParameters());
				Object obj = context.getJpaOperations().updateWithoutNull(entity,
						BeanUtil.getExtDatas(entity, context.getParameters()));
				context.add(oid, obj);
			}
		} else if (key.startsWith("update.")) {
			String entityType = key.substring(7);
			OperationId oid = FastDevUtils.operationId(entityType);
			Object obj = null;
			if (StringUtils.isEmpty(prop)) {
				Object entity = context.getClassMappingFactory().getEntity(oid.getId(), context.getParameters());
				obj = context.getJpaOperations().update(entity, BeanUtil.getExtDatas(entity, context.getParameters()));
			} else {
				obj = context.getJpaOperations().updateBySql(prop, context.getParameters());
			}
			context.add(oid, obj);

		} else if (key.startsWith("updateWithoutNull.")) {
			String entityType = key.substring(14);
			OperationId oid = FastDevUtils.operationId(entityType);
			Object obj = null;
			if (StringUtils.isEmpty(prop)) {
				Object entity = context.getClassMappingFactory().getEntity(oid.getId(), context.getParameters());
				obj = context.getJpaOperations().update(entity, BeanUtil.getExtDatas(entity, context.getParameters()));
			} else {
				obj = context.getJpaOperations().updateBySql(prop, context.getParameters());
			}
			context.add(oid, obj);
		}
	}

}
